package cn.leida.ruoyi.generator.dao;

import cn.hutool.core.util.StrUtil;
import cn.leida.ruoyi.common.core.dao.BaseDao;
import cn.leida.ruoyi.generator.dto.GenTableColumnDto;
import cn.leida.ruoyi.generator.domain.GenTableColumn;
import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class GenTableColumnDaoCustomImpl extends BaseDao implements GenTableColumnDaoCustom {


    @Override
    public List<GenTableColumn> findDbTableColumnsByName(String tableName) {
        List<Object> params = new ArrayList<>();

        String baseSql = """
             select
             	column_name columnName,
             	(case when (is_nullable = 'no' && column_key != 'PRI') then '1' else null end) as isRequired ,
             	(case when column_key = 'PRI' then '1' else '0' end) as isPk, ordinal_position as sort,
             	column_comment as columnComment ,
             	(case when extra = 'auto_increment' then '1' else '0' end) as isIncrement,
             	column_type as columnType
            from
            	information_schema.columns
                        
            where table_schema = (select database())
                        
            """;
        StringBuilder sql = new StringBuilder();
        sql.append(baseSql);
        if (StrUtil.isNotBlank(tableName)) {
            sql.append(" and table_name = ? ");
            params.add(tableName);
        }
        sql.append(" order by ordinal_position ");

        List<JSONObject> jsonObjectList = queryData(sql.toString(), params);
        List<GenTableColumn> dataList = GenTableColumnDto.loadBeans(jsonObjectList);

        return dataList;
    }


}
